﻿using NewsReader.Helpers;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NewsReader.ViewModels;
using NewsReader.Helpers.Orm;
using NewsReader.Log;

namespace NewsReaderApp.ViewModels
{
    internal class SettingsViewModel : INotifyPropertyChanged, IApplyable
    {
        public event PropertyChangedEventHandler PropertyChanged;

        public int RefreshFrequencyMinutes
        {
            get { return SettingsManager.Instance.GetValue<int>(SupportedSettings.RefreshFrequencyMinutes); }
            set
            {
                if (SettingsManager.Instance.GetValue<int>(SupportedSettings.RefreshFrequencyMinutes) != value)
                {
                    SettingsManager.Instance.SetValue(SupportedSettings.RefreshFrequencyMinutes, value);
                    this.RaisePropertyChanged(PropertyChanged, "RefreshFrequencyMinutes");
                }
            }

        }

        public int DeleteItemsOlderThanDays
        {
            get { return SettingsManager.Instance.GetValue<int>(SupportedSettings.DeleteItemsOlderThenDays); }
            set
            {
                if (SettingsManager.Instance.GetValue<int>(SupportedSettings.DeleteItemsOlderThenDays) != value)
                {
                    SettingsManager.Instance.SetValue(SupportedSettings.DeleteItemsOlderThenDays, value);
                    this.RaisePropertyChanged(PropertyChanged, "DeleteItemsOlderThenDays");
                }
            }
        }


        public NewsFormatter SelectedNewsFormatter
        {
            get
            {
                var nf = NewsFormatter.Named(SettingsManager.Instance.GetValue<string>(SupportedSettings.ParserEngine));
                Logger.Log.DebugFormat("Selected NewsFormatter is {0}", nf.Name);
                return nf;
            }
            set
            {
                if (SettingsManager.Instance.GetValue<string>(SupportedSettings.ParserEngine) != value.Name)
                {
                    SettingsManager.Instance.SetValue(SupportedSettings.ParserEngine, value.Name);
                    this.RaisePropertyChanged(PropertyChanged, "SelectedNewsFormatter");
                }
            }
        }

        public IEnumerable<NewsFormatter> AllNewsFormatters
        {
            get { return NewsFormatter.All; }
        }


        public async Task Apply()
        {
            await App.RegisterBackgroundTaskAsync();
            await SettingsManager.Instance.SaveSettingsAsync();
        }
    }
}
